import {
    Image,
    StyleSheet,
    View,
    Text,
    TouchableOpacity,
    FlatList,
    ScrollView,
    Platform,
    Alert,
    Linking, PermissionsAndroid
} from 'react-native';
import {Stack, useRouter} from "expo-router";
import AntDesign from '@expo/vector-icons/AntDesign';
import CityData from "@/assets/json/city.json"
import { pinyin } from 'pinyin-pro';
import {useRef, useState, useEffect, useCallback} from "react";
import LocationIcon from "@/assets/images/homeImg/locationIcon.png"
import * as Location from 'expo-location';
import {useDispatch, useSelector} from "react-redux";
import {RootState} from "@/store";
import cityList from "@/assets/json/city"
import {getGrainInfoDetail, getUserInfoDetail, setLocationInfo} from "@/store/slices/loginSlice";
import 'intl';
import 'intl/locale-data/jsonp/zh-Hans-CN';
import {check, PERMISSIONS, request, RESULTS} from "react-native-permissions";
import Geolocation from "react-native-geolocation-service";
import axios from "axios/index";
import {txApiKey} from "@/config/config-params";
import {getImTokenAdmin} from "@/services/login";
import {getOpenImSelfByToken} from "@/services/openImServices";
import {initSDK, platformID} from "@/utils/ImCommon";
import {useFocusEffect} from "@react-navigation/native";

const HEADER_HEIGHT = 40;
const ITEM_HEIGHT = 40;

export default function searchCityScreen() {

    const router = useRouter();
    const [highlightLetter, setHighlightLetter] = useState(null); // 高亮的字母
    const [location, setLocation] = useState(null);
    const [errorMsg, setErrorMsg] = useState(null);
    const [address, setAddress] = useState(null);

    const dispatch = useDispatch();

    const login = useSelector((state: RootState) => state.login);

    // useEffect(() => {
    //     getImTokenAdmin()
    //         .then(res => {
    //             const adminToken = res?.data?.imAdminToken;
    //             getOpenImSelfByToken(adminToken, login?.userInfo?.uid, platformID)
    //                 .then(r => {
    //                     console.log('r', r.data.token);
    //                     initSDK(login?.userInfo?.uid, r.data.token);
    //                 })
    //                 .catch(e => {
    //                     console.log('e', e);
    //                 });
    //             console.log('getImTokenAdmingetImTokenAdmingetImTokenAdmin', res);
    //         })
    //         .catch(err => {
    //             console.log('err', err);
    //         })
    //
    // }, [login.userInfo])

    useFocusEffect(
        useCallback(() => {
            dispatch(getUserInfoDetail());
            dispatch(getGrainInfoDetail());
            // setIndex(index)
            return () => console.log("Tab unfocused");
        }, [])
    );

    useEffect(() => {
        console.log('login', login);
    }, [login]);

    const requestLocationPermission = async () => {
        if (Platform.OS === 'android') {
            const granted = await PermissionsAndroid.request(
                PermissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION,
                {
                    title: 'Location Permission',
                    message: 'We need access to your location to show you...',
                    buttonNeutral: 'Ask Me Later',
                    buttonNegative: 'Cancel',
                    buttonPositive: 'OK',
                }
            );
            return granted === PermissionsAndroid.RESULTS.GRANTED;
        }
        return true; // iOS always grants permission via settings
    };

    const getLocation = async () => {
        const hasPermission = await requestLocationPermission();
        if (!hasPermission) {
            // console.log('Location permission denied');
            return;
        }

        // console.log('locationInfolocationInfo', login.locationInfo)


        Geolocation.getCurrentPosition(
            (position) => {
                const { latitude, longitude } = position.coords;
                if (login.locationInfo?.ad_info) return;
                axios.get(`https://apis.map.qq.com/ws/geocoder/v1?key=${txApiKey}&location=${latitude},${longitude}&get_poi=1`)
                    .then(res => {
                        const data = res.data.result;
                        console.log('res', res);
                        console.log('getCurrentPositiongetCurrentPositiongetCurrentPosition', data)
                        const locationData = {
                            province: data?.ad_info?.province || data?.address_component?.nation,
                            city: data?.ad_info?.city || data?.address_component?.locality,
                            location: data?.location,
                        };

                        if (res.data.message == 'Success') {
                            dispatch(setLocationInfo({ locationInfo: locationData }));
                        };

                    })
                    .catch(err => {
                        console.log('err', err);
                    })
            },
            (error) => {
                console.warn(error.message);
            },
            { enableHighAccuracy: true, timeout: 15000, maximumAge: 10000 }
        );
    };

    // 拼音分组并排序
    const groupByInitialLetter = (data) => {
        const grouped = data.reduce((acc, item) => {
            const getFirstPinyinLetter = (text) => {
                if (!text) return '';
                return pinyin(text[0], { pattern: 'first', toneType: 'none' }).toUpperCase();
            };


            const firstLetter = getFirstPinyinLetter(item.name);
            const existingGroup = acc.find(group => group.letter === firstLetter);

            if (existingGroup) {
                existingGroup.cities.push(item.name);
            } else {
                acc.push({ letter: firstLetter || "", cities: [item.name] || [] });
            }

            return acc;

        }, []);

        console.log("grouped", grouped);

        return grouped.sort((a, b) => a.letter.localeCompare(b.letter));
    };

    const DATA = groupByInitialLetter(CityData);

    console.log('DATA', DATA);

// 高度常量

    const flatListRef = useRef(null);

    // 计算每个字母组的偏移量
    const calculateOffset = (index) => {
        let offset = 0;
        for (let i = 0; i < index; i++) {
            offset += HEADER_HEIGHT + DATA[i].cities.length * ITEM_HEIGHT;
        }
        return offset;
    };

    // 直接定位到对应字母
    const scrollToOffset = (index) => {
        const offset = calculateOffset(index) + 205;
        flatListRef.current.scrollToOffset({ offset, animated: false });
    };

    // 监听滚动事件
    const handleScroll = (event) => {
        const offsetY = event.nativeEvent.contentOffset.y - 205;
        let accumulatedOffset = 0;

        for (let i = 0; i < DATA.length; i++) {
            const sectionHeight = HEADER_HEIGHT + DATA[i].cities.length * ITEM_HEIGHT;
            accumulatedOffset += sectionHeight;

            if (offsetY < accumulatedOffset) {
                setHighlightLetter(DATA[i].letter);
                break;
            }
        }
    };

    const cutCity = function (city) {
        let tmpProvinces = ''
        cityList.forEach((item,index) => {
            item.city.forEach((itt, idx) => {
                if (itt.name == city) {
                    tmpProvinces = item.name
                    console.log(city+'位于省份：', item.name)
                }
            })
        })
        dispatch(setLocationInfo({ locationInfo: { province: tmpProvinces || "", city }}));
        router.back();
    };

    // 渲染城市项
    const renderCity = ({ item }) => (
        <TouchableOpacity onPress={() => cutCity(item)}>
            <View style={styles.cityContainer}>
                <Text style={styles.cityText}>{item}</Text>
            </View>
        </TouchableOpacity>

    );

    // 渲染字母分组和城市列表
    const renderCategory = ({ item }) => (
        <View style={{ paddingLeft: 12, paddingRight: 12, }}>
            <View style={styles.categoryContainer}>
                <Text style={styles.categoryText}>{item.letter}</Text>
            </View>
            <FlatList
                data={item.cities}
                renderItem={renderCity}
                keyExtractor={(city) => city}
                scrollEnabled={false} // 禁用内部滚动
            />
        </View>
    );

    const ListHeaderComponent = function () {
        const login = useSelector((state: RootState) => state.login);

        useEffect(() => {
            console.log('login', login);
        }, [login.locationInfo])

        const checkLocationPermission = async () => {
            const permission = Platform.OS === 'ios'
                ? PERMISSIONS.IOS.LOCATION_WHEN_IN_USE
                : PERMISSIONS.ANDROID.ACCESS_FINE_LOCATION;

            const result = await check(permission);

            if (result === RESULTS.GRANTED) {
                console.log("定位权限已授权");
                getLocation();
                return true;
            } else if (result === RESULTS.DENIED) {
                // 请求权限
                const requestResult = await request(permission);
                return requestResult === RESULTS.GRANTED;
            } else {
                // 用户拒绝，无法再次请求，引导去设置
                Alert.alert(
                    "需要定位权限",
                    "请在设置中开启定位权限，以使用该功能。",
                    [
                        { text: "取消", style: "cancel" },
                        { text: "去设置", onPress: () => Linking.openSettings() }
                    ]
                );
                return false;
            }
        };

        return (
            <View style={{ height: 205}}>
                <View style={ styles.currentPotionContainer }>
                    <View style={styles.currentPotion}>
                        <Text style={styles.currentPotionText}>当前定位</Text>
                    </View>
                    <View style={styles.cityWarp}>
                        <View style={styles.locationIconImg}>
                            <Image source={LocationIcon} style={{ width: "100%", height: "100%" }} />
                        </View>
                        {
                            login?.locationInfo?.city && (
                                <View style={styles.cityName}>
                                    <Text>{ login?.locationInfo?.city }</Text>
                                </View>
                            )
                        }

                        {
                            !login?.locationInfo?.city && (
                              <TouchableOpacity onPress={checkLocationPermission}>
                                  <View style={styles.cityName}>
                                      <Text>重新获取城市定位</Text>
                                  </View>
                              </TouchableOpacity>
                            )
                        }
                    </View>
                </View>
                <View style={styles.hotCityContainer}>
                    <View style={styles.hotCityTitle}>
                        <Text style={styles.hotCityTitleText}>热门城市</Text>
                    </View>
                    <View style={styles.hotCityListWarp}>
                        <TouchableOpacity onPress={() => cutCity("上海市")}>
                            <View style={styles.hotCityItem}>
                                <Text style={styles.hotCityItemText}>上海市</Text>
                            </View>
                        </TouchableOpacity>
                        <TouchableOpacity onPress={() => cutCity("成都市")}>
                            <View style={styles.hotCityItem}>
                                <Text style={styles.hotCityItemText}>成都市</Text>
                            </View>
                        </TouchableOpacity>
                       <TouchableOpacity onPress={() => cutCity("重庆市")}>
                           <View style={styles.hotCityItem}>
                               <Text style={styles.hotCityItemText}>重庆市</Text>
                           </View>
                       </TouchableOpacity>
                    </View>
                    <View style={styles.hotCityListWarp}>
                        <TouchableOpacity onPress={() => cutCity("青岛市")}>
                            <View style={styles.hotCityItem}>
                                <Text style={styles.hotCityItemText}>青岛市</Text>
                            </View>
                        </TouchableOpacity>
                        <TouchableOpacity onPress={() => cutCity("北京市")}>
                            <View style={styles.hotCityItem}>
                                <Text style={styles.hotCityItemText}>北京市</Text>
                            </View>
                        </TouchableOpacity>
                        <TouchableOpacity onPress={() => cutCity("杭州市")}>
                            <View style={styles.hotCityItem}>
                                <Text style={styles.hotCityItemText}>杭州市</Text>
                            </View>
                        </TouchableOpacity>
                    </View>
                </View>
            </View>
        )
    };


    return (
        <View style={{ height: "100%", backgroundColor: "#FFF" }}>
            <Stack.Screen
                options={{
                    title: '选择城市', // 设置屏幕标题
                    headerStyle: {
                        backgroundColor: '#FFF', // 设置标题栏的背景颜色
                    },
                    headerShadowVisible: false, // 隐藏底部阴影和边框
                    headerBackTitleVisible: false,
                    headerTintColor: "#333",
                    headerLeft: () => (
                        <TouchableOpacity onPress={() => router.back()}>
                            <AntDesign name="left" size={19} color="#333" />
                        </TouchableOpacity>
                    ),
                }}
            />
            <View style={styles.container}>
                <View style={styles.listContainer}>
                    <FlatList
                        ref={flatListRef}
                        data={DATA}
                        renderItem={renderCategory}
                        keyExtractor={(item) => item.letter}
                        onScroll={handleScroll} // 监听滚动事件
                        getItemLayout={(data, index) => ({
                            length: HEADER_HEIGHT + data[index].cities.length * ITEM_HEIGHT,
                            offset: calculateOffset(index),
                            index
                        })}
                        ListHeaderComponent={ListHeaderComponent}
                    />
                </View>
                <View style={styles.sidebar}>
                    <ScrollView>
                        {
                            DATA.map((item, index) => (
                                <TouchableOpacity
                                    key={item.letter}
                                    style={[styles.sidebarItem]}
                                    onPress={() => scrollToOffset(index)} // 直接定位到字母
                                >
                                    <Text style={[styles.sidebarText,highlightLetter === item.letter && styles.highlightedText]}>{item.letter}</Text>
                                </TouchableOpacity>
                            ))
                        }
                    </ScrollView>
                </View>
            </View>
        </View>

    );
}

const styles = StyleSheet.create({
    container: {
        flexDirection: 'row',
    },
    listContainer: {
        flex: 1,
        // padding: 10,
    },
    sidebar: {
        position: "absolute",
        width: 30,
        padding: 10,
        right: 5,
        top: 100,
    },
    sidebarItem: {
        marginVertical: 5,
    },
    sidebarText: {
        fontSize: 12,
        textAlign: 'center',
        color: "#9E9E9E"
    },
    categoryContainer: {
        height: HEADER_HEIGHT,
        justifyContent: 'center',
        // paddingHorizontal: 10,
    },
    categoryText: {
        fontSize: 12,
        color: "#2A2B30"
    },
    cityContainer: {
        // padding: 10,
        height: ITEM_HEIGHT,
        borderBottomWidth: 0.2,
        borderBottomColor: '#E4E6EC',
        flexDirection: "row",
        alignItems: "center",
        marginRight:25,
    },
    cityText: {
        fontSize: 12,
    },
    currentPotion: {
        paddingLeft: 12,
        paddingRight: 12,
    },
    currentPotionText: {
        color: "#9E9E9E",
        fontSize: 14,
        marginTop: 5,
    },
    locationIconImg: {
        width: 13,
        height: 13,
    },
    cityWarp: {
        flexDirection: "row",
        marginTop: 10,
        paddingBottom: 14,
        borderBottomWidth: 6,
        borderBottomColor: "#F7F7F7",
        paddingLeft: 12,
        paddingRight: 12,
        alignItems: "center",
    },
    cityName: {
        marginLeft: 2,
    },
    currentPotionContainer: {
    },
    hotCityContainer: {
        paddingLeft: 12,
        paddingRight: 12,
    },
    hotCityTitle: {
        marginTop: 14,
    },
    hotCityTitleText: {
        color: "#9E9E9E",
    },
    hotCityListWarp: {
        flexDirection: "row",
        justifyContent: "space-around",
        paddingRight: 25,
        marginTop: 10,
    },
    hotCityItem: {
        width: 104,
        height: 34,
        backgroundColor: "#F7F8F9",
        borderRadius: 4,
        flexDirection: "row",
        justifyContent: "center",
        alignItems: "center",
    },
    hotCityItemText: {
        fontSize: 14,
        color: "#2A2B30",
        // fontWeight: 500,
    },
    highlightedText: {
        color: "#EC6138",
    },
});
